package methods;


import org.rsbuddy.tabs.Inventory;

import com.rsbuddy.script.methods.Npcs;
import com.rsbuddy.script.methods.Players;
import com.rsbuddy.script.methods.Widgets;
import com.rsbuddy.script.task.Task;
import com.rsbuddy.script.util.Timer;
import com.rsbuddy.script.wrappers.Component;
import com.rsbuddy.script.wrappers.Npc;
import com.rsbuddy.script.wrappers.Widget;

public class Shop{
	
	public static final int WIDGET_SHOP = 620;
	public static final int WIDGET_SHOP_CLOSE = 18;
	public static final int NPC_ID = 8864;
	public static final int WIDGET_SHOP_STOCKS = 25;
	public static final int[] WIDGET_SHOP_ITEMS = {2, 8, 14, 20, 26, 32, 38, 44, 50, 56, 62, 68, 74, 80, 86, 92, 98, 104};
	
	private static boolean canBuy(int itemId){
		if(isOpen()){
			for(int i : WIDGET_SHOP_ITEMS){
				Component w = getWidget().getComponent(WIDGET_SHOP_STOCKS).getComponent(i+2);
				if(Integer.parseInt(w.getText()) <= Inventory.getCount(true, 995)){
					return true;
				}
			}
		}
		return false;
	}
	
	public static boolean getCount(int itemId){
		if(isOpen()){
			for(int i : WIDGET_SHOP_ITEMS){
				Component w = getWidget().getComponent(WIDGET_SHOP_STOCKS).getComponent(i);
				if(w.getItemId() == itemId && w.getItemStackSize() != 0){
					return true;
				}
			}
		}
		return false;
	}
	
	public static boolean buy(int itemId, int count){
		if(isOpen()){
			for(int i : WIDGET_SHOP_ITEMS){
				Component w = getWidget().getComponent(WIDGET_SHOP_STOCKS).getComponent(i);
				if(w.getItemId() ==  itemId && getCount(itemId) && canBuy(itemId)){
					return w != null && w.interact("Buy "+ count);
				}else if(!getCount(itemId) || !canBuy(itemId)){
					return close();
				}
			}
		}
		return false;
	}
		
	public static void wait(boolean act, int time){
		Timer timeout = new Timer (time);
		do{
			Task.sleep(15);
		} while(act && timeout.isRunning());
	}
	
	public static boolean close() {
		if (isOpen()) {
			Component button = getWidget().getComponent(WIDGET_SHOP_CLOSE);
			return button.click();
		}
		return false;          
	}
	
	public static boolean open() {
		if (!isOpen()) {
			Npc npc = Npcs.getNearest(NPC_ID);
			if (npc == null) {
				return false;
			}
			npc.interact("Trade " + npc.getName());
			if (Players.getLocal().isMoving()) {
				do {
					Task.sleep(15);
				} while (Players.getLocal().isMoving());
			}
			Timer timeout = new Timer(1200);
			do{
				Task.sleep(15);
			} while (!isOpen() && timeout.isRunning());
		}
		return isOpen();
	} 
	
	public static boolean isOpen(){
		if(isValid()){
			return getWidget().getComponent(1).isVisible();
		}
		return false;
	}
	
	public static boolean isValid(){
		Widget w = getWidget();
		return w != null && w.isValid();
	}
	
	public static Widget getWidget(){
		return Widgets.get(WIDGET_SHOP);
	}
	
}
